import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutterhello/api/api.dart';
import 'package:flutterhello/controller/Controller.dart';
import 'package:flutterhello/widgets/loading_dialog.dart';
import 'package:flutterhello/widgets/my_toast.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart' as MyGet;

import '../../../my_app.dart';

class ReviseInfoPage extends StatefulWidget {
  @override
  _ReviseInfoPageState createState() => _ReviseInfoPageState();
}

class _ReviseInfoPageState extends State<ReviseInfoPage> {
  GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  List<Asset> images = [];
  String _error;

  Future<void> loadAssets() async {
    List<Asset> resultList;
    String error;

    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 1,
        enableCamera: true,
      );
    } on Exception catch (e) {
      error = e.toString();
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      images = images + resultList;
      if (error == null) _error = 'No Error Dectected';
      print(_error);
    });
  }

  Widget buildGridView1() {
    if (images.length == 0)
      return GridView.count(
        crossAxisCount: 3,
        children: [
          Row(
            children: [Text('选择头像')],
          ),
          Container(),
          Container(
            height: 120,
            width: 120,
            decoration: BoxDecoration(
              border: Border(
                  left: BorderSide(width: 1, color: Colors.black26),
                  right: BorderSide(width: 1, color: Colors.black26),
                  bottom: BorderSide(width: 1, color: Colors.black26),
                  top: BorderSide(width: 1, color: Colors.black26)),
              borderRadius: BorderRadius.circular(5),
            ),
            child: IconButton(
              icon: Icon(Icons.add),
              onPressed: loadAssets,
            ),
          ),
        ],
      );
    else {
      Asset asset = images[0];
      return GridView.count(
        crossAxisCount: 3,
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
        children: [
          Row(
            children: [Text('选择头像')],
          ),
          Container(),
          Container(
            width: 300,
            height: 300,
            child: Stack(
              children: [
                Align(
                  alignment: Alignment(0, 0),
                  child: AssetThumb(
                    asset: asset,
                    width: 300,
                    height: 300,
                  ),
                ),
                Align(
                  alignment: Alignment(0.9, -0.9),
                  child: GestureDetector(
                    child: Icon(
                      const IconData(0xe600, fontFamily: "alIcons"),
                      size: 15,
                      color: Colors.blueGrey,
                    ),
                    onTap: () {
                      setState(() {
                        this.images.removeAt(0);
                      });
                    },
                  ),
                )
              ],
            ),
          )
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        child: AppBar(
          title: Text('修改用户信息'),
          centerTitle: true,
        ),
        preferredSize: Size.fromHeight(50),
      ),
      body: Container(
        child: Padding(
          padding: EdgeInsets.all(15),
          child: Column(
            children: [
              Expanded(
                flex: 1,
                child: Padding(
                  padding: EdgeInsets.only(top: 10),
                  child: buildGridView1(),
                ),
              ),
              GestureDetector(
                child: Container(
                  height: 50,
                  width: double.infinity,
                  decoration: BoxDecoration(
                    color: Colors.blueGrey,
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                  ),
                  child: Center(
                    child: Text(
                      '提 交',
                      style: TextStyle(color: Colors.white, fontSize: 20),
                    ),
                  ),
                ),
                onTap: () async {
                  var result = await showDialog(
                      context: context,
                      builder: (context) {
                        return AlertDialog(
                          title: Text('提示'),
                          content: Text('确认创建吗？'),
                          actions: <Widget>[
                            TextButton(
                              child: Text('取消'),
                              onPressed: () {
                                Navigator.of(context).pop('cancel');
                              },
                            ),
                            TextButton(
                              child: Text('确认'),
                              onPressed: () {
                                submit(images, context);
                              },
                            ),
                          ],
                        );
                      });
                  print('$result');
                },
              ),
              SizedBox(
                height: 400,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

submit(images, context) async {
  if (images.length != 0) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return new LoadingDialog(
          text: "上传中…",
        );
      },
    );
    FormData formData = new FormData.fromMap({});
    for (int i = 0; i < images.length; i++) {
      ByteData byteData = await images[i].getByteData();
      List<int> imageData = byteData.buffer.asUint8List();
      MultipartFile multipartFile = MultipartFile.fromBytes(
        imageData,
        filename: images[i].name,
      );
      formData.files.addAll([
        MapEntry("file", multipartFile),
      ]);
    }
    var res = await Api.uploadImg(formData);
    if (res['code'] == 1000) {
      var res2 = await Api.reviseUserInfo({"favicon": res['data'][0]});
      if (res2['code'] == 1000) {
        Navigator.of(context).pop();
        MyTost.showTost(res2['message']);
        final controller = MyGet.Get.put(Controller());
        await controller.loginRs();
        MyGet.Get.offAll(MyApp());
      } else {
        MyTost.showTost('上传失败');
        Navigator.of(context).pop();
      }
    }
  } else {
    MyTost.showTost('头像必填');
  }
}
